#include "InputHID.h"


bool CInputHID::CreateInputListener(HWND hwnd)
{
	RAWINPUTDEVICE rid[2];

	rid[0].usUsagePage = HID_USAGE_PAGE_GENERIC;
	rid[0].usUsage = HID_USAGE_GENERIC_MOUSE;
	rid[0].dwFlags = 0;
	rid[0].hwndTarget = hwnd;

	rid[1].usUsagePage = HID_USAGE_PAGE_GENERIC;
	rid[1].usUsage = HID_USAGE_GENERIC_KEYBOARD;
	rid[1].dwFlags = 0;// RIDEV_NOLEGACY;
	rid[1].hwndTarget = hwnd;

	BOOL ret = RegisterRawInputDevices(rid, 2, sizeof(RAWINPUTDEVICE));

	return (ret == TRUE);
}


void CInputHID::Update(RAWINPUT* rawData, UINT numRawData, bool background)
{
	if(rawData != NULL)
	{
		switch(rawData->header.dwType)
		{
		case RIM_TYPEMOUSE:
			{
				RAWMOUSE* raw = &rawData->data.mouse;

				_mouseInfo.posXrelative = raw->lLastX;
				_mouseInfo.posYrelative = raw->lLastY;


				USHORT flags = raw->usButtonFlags;

				if(flags & RI_MOUSE_WHEEL)
					_mouseInfo.wheelDelta += (SHORT)raw->usButtonData;

				if(flags & RI_MOUSE_LEFT_BUTTON_DOWN)
					_mouseInfo.btn1Down = true;
				
				if(flags & RI_MOUSE_LEFT_BUTTON_UP)
					_mouseInfo.btn1Down = false;

				if(flags & RI_MOUSE_RIGHT_BUTTON_DOWN)
					_mouseInfo.btn2Down = true;

				if(flags & RI_MOUSE_RIGHT_BUTTON_UP)
					_mouseInfo.btn2Down = false;

				if(flags & RI_MOUSE_MIDDLE_BUTTON_DOWN)
					_mouseInfo.btn3Down = true;

				if(flags & RI_MOUSE_MIDDLE_BUTTON_UP)
					_mouseInfo.btn3Down = false;

			}
			break;
		case RIM_TYPEKEYBOARD:
			{
				RAWKEYBOARD* raw = &rawData->data.keyboard;

				bool keyRelease = (raw->Flags & RI_KEY_BREAK);
				int index = -1;

				for(int i=0; i<5; ++i)
				{
					if(keyRelease)
					{
						if(_keyboardInfo.keyPressed[i] == raw->VKey)
						{
							_keyboardInfo.keyPressed[i] = 0;
							break;
						}
					}
					else
					{
						if(_keyboardInfo.keyPressed[i] == raw->VKey)
						{
							index = -1;
							break;
						}

						if(_keyboardInfo.keyPressed[i] == 0)
						{
							index = i;
						}
					}
				}

				if(!keyRelease && 
					index > -1)
				{
					_keyboardInfo.keyPressed[index] = raw->VKey;
				}
			}
			break;
		case RIM_TYPEHID:
			{

			}
			break;
		}
	}
}


void CInputHID::ResetOnIdle()
{
	_mouseInfo.wheelDelta = 0;
}